package com.mediocre.customLogin.filter;

import com.mediocre.common.util.WebUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 张伟
 * @desc
 * @date 2022/1/2 下午2:33
 * @modifier
 */
@Component
public class VerifyCodeFilter extends GenericFilterBean {
    private String defaultFilterProcessUrl = "/doLogin";

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        if ("POST".equalsIgnoreCase(request.getMethod()) && defaultFilterProcessUrl.equals(request.getServletPath())) {
            // 验证码验证
            String requestCaptcha = request.getParameter("code");
            String genCaptcha = (String) request.getSession().getAttribute("verify_code");
            if (!StringUtils.hasText(genCaptcha)) {
                // throw new AuthenticationServiceException("验证码不能为空!");
                // 抛异常的话，前端无法显示该异常消息，所以直接将异常消息以json格式返回到前端
                WebUtils.out(response, "请先生成一个验证码!");
                return;
            } else if (!StringUtils.hasText(requestCaptcha)) {
                // throw new AuthenticationServiceException("验证码不能为空!");
                // 抛异常的话，前端无法显示该异常消息，所以直接将异常消息以json格式返回到前端
                WebUtils.out(response, "验证码不能为空!");
                return;
            } else if (!genCaptcha.equalsIgnoreCase(requestCaptcha)) {
                // throw new AuthenticationServiceException("验证码错误!");
                WebUtils.out(response, "验证码错误!");
                return;
            }
        }
        chain.doFilter(request, response);
    }
}
